package streamer.webapp.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DefaultTreeNode;
import streamer.webapp.displaybeans.FileTreeNode;
import streamer.webapp.displaybeans.URITreeNode;
import streamer.webapp.util.MagicTool;

@ManagedBean
@SessionScoped
public class OverviewAction extends AbstractWebAction{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1735126407910388130L;
	private String welcomemessage = "Welcome";

	private DefaultStreamedContent stream;
	private String streamPath;
	private boolean mp3PlayerDisplayed = false;
	private boolean videoPlayerDisplayed = false;
	private String playerHeight;
	private List<File> playList;
	private File selectedResource;
	
	private static String AUDIO_PLAYER_HEIGHT = "60";
		
	@PostConstruct
	public void load() {
		playList = new ArrayList<File>();
	}
	
	public void onNodeSelect(NodeSelectEvent event) {
		treeBean.onNodeSelect(event);
		
		DefaultTreeNode node = getTreeBean().getSelectedNode();
		
		boolean load = true;
		
		if(node instanceof FileTreeNode){
			FileTreeNode tNode = (FileTreeNode)node;
			if(tNode.getFile() != null && tNode.getFile().isDirectory())
				load = false;
		}
				
		if(load){
			loadStream();
		}
	}
	
	public void loadNextStream(){
		System.out.println("load next stream");
	}
	
	public void addToPlayList(){
		DefaultTreeNode node = getTreeBean().getSelectedNode();
		
		if(node instanceof FileTreeNode){
			FileTreeNode tNode = (FileTreeNode)node;
			if(tNode.getFile() != null && tNode.getFile().isDirectory()){
				List<File> children = MagicTool.getOnlyFiles(tNode.getFile());
				playList.addAll(children);
			}
			else if(tNode.getFile() != null && tNode.getFile().getAbsolutePath().endsWith(".mp3")){
				playList.add(tNode.getFile());
			} else if(tNode.getFile() != null && tNode.getFile().getAbsolutePath().endsWith(".avi")){
				playList.add(tNode.getFile());
			}
		}
	}
	
	public void emptyPlayList(){
		if(playList != null)
			playList.clear();
	}
	
	public void playSelectedResource(){
		if(selectedResource != null){
			loadFile(selectedResource);
		}
	}
	
	public void playNext(){
		if(selectedResource != null && playList != null){
			
			int index = playList.indexOf(selectedResource);
			if(index < playList.size() -1 ){
				selectedResource = playList.get(index+1);
			} else {
				selectedResource = playList.get(0);
			}
			
			playSelectedResource();
		}
	}
	
	public void playPrevious(){
		if(selectedResource != null && playList != null){
			
			int index = playList.indexOf(selectedResource);
			if(index >  0 ){
				selectedResource = playList.get(index-1);
			} else {
				selectedResource = playList.get(playList.size()-1);
			}
			
			playSelectedResource();
		}
	}
	
	public void removeSelectedResource(){
		if(selectedResource != null && playList != null){
			playList.remove(selectedResource);
		}
	}
	
	
	private void loadFile(File file){
		if (file != null) {
			if (file.getAbsolutePath().endsWith(".mp3")) {
				String mp3FolderPath = FacesContext.getCurrentInstance()
						.getExternalContext().getRealPath("resources/mp3");
				String mp3FilePath = file.getAbsolutePath();
				/*if (mp3FilePath.contains(mp3FolderPath)) {
					String filteredPath = mp3FilePath
							.replace(mp3FolderPath, "");
					streamPath = "../resources/mp3/" + filteredPath.replaceAll(" ", "%20");
					playerHeight = AUDIO_PLAYER_HEIGHT;
					mp3PlayerDisplayed = true;
					videoPlayerDisplayed = false;
				}*/
				FacesContext fCtx = FacesContext.getCurrentInstance();
				
				HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
				String sessionId = session.getId();
				
				//String usrId = "user1";
				String dstPath = mp3FolderPath+"/"+sessionId+".mp3";
				try {
					copyFile(mp3FilePath, dstPath);
				
					streamPath = "../resources/mp3/"+sessionId+".mp3";
				} catch (IOException e) {
					e.printStackTrace();
				}
				playerHeight = AUDIO_PLAYER_HEIGHT;
				mp3PlayerDisplayed = true;
				videoPlayerDisplayed = false;
				
			} else if(file.getAbsolutePath().endsWith(".avi")){
				String videoFolderPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("resources/video");
				String videoFilePath = file.getAbsolutePath();
				if(	videoFilePath.contains(videoFolderPath) ){
					String filteredPath = videoFilePath.replace(videoFolderPath, "");
					streamPath = "../resources/video/"+filteredPath.replaceAll(" ", "%20").replace("\\", "");
					mp3PlayerDisplayed = false;
					videoPlayerDisplayed = true;
				}
			}
		}
	}
	
	private void copyFile(String filePath, String dstPath) throws IOException {
		File srcFile = new File(filePath);
		if (srcFile.exists()) {
			if (srcFile.isFile()) {
				File dstFile = new File(dstPath);
				InputStream in = new FileInputStream(srcFile);
				OutputStream out = new FileOutputStream(dstFile);

				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}

				in.close();
				out.close();
			}
		}
	}
	
	public void loadStream(){
		DefaultTreeNode node = getTreeBean().getSelectedNode();
		
		if(node instanceof FileTreeNode){
			FileTreeNode tNode = (FileTreeNode)node;
			loadFile(tNode.getFile());
		} else if(node instanceof URITreeNode){
			URITreeNode uNode = (URITreeNode)node;
			stream = null;
			streamPath = uNode.getFilePath();
			playerHeight = AUDIO_PLAYER_HEIGHT;
			mp3PlayerDisplayed = true;
			videoPlayerDisplayed = false;
		}
	}
	
	public String getWelcomemessage() {
		return welcomemessage;
	}

	public void setWelcomemessage(String welcomemessage) {
		this.welcomemessage = welcomemessage;
	}

	public Object getStream() {
		if(stream != null)
			return stream;
		else 
			return streamPath;		
	}

	public String getPlayerHeight() {
		return playerHeight;
	}

	public boolean isMp3PlayerDisplayed() {
		return mp3PlayerDisplayed;
	}

	public boolean isVideoPlayerDisplayed() {
		return videoPlayerDisplayed;
	}

	public List<File> getPlayList() {
		return playList;
	}

	public File getSelectedResource() {
		return selectedResource;
	}

	public void setSelectedResource(File selectedResource) {
		this.selectedResource = selectedResource;
	}
}
